/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CadastroReserva.java
 *
 * Created on 05/07/2011, 19:51:10
 */
package Formularios;

import DAO.ReservaDAO;
import Logica.Reserva;
import java.awt.Color;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.sql.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;

/**
 *
 * @author Pedro H
 */
public class CadastroReserva extends javax.swing.JFrame {

    int idsala;
    int iduser;

    /** Creates new form CadastroReserva */
    public CadastroReserva(int idsala, int iduser) {
        initComponents();
        setLocationRelativeTo(null);
        
        this.idsala = idsala;
        this.iduser = iduser;
    }

    public CadastroReserva() {
        initComponents();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jCalendar1 = new com.toedter.calendar.JCalendar();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTData = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTIdSala = new javax.swing.JTextField();
        jTIdUser = new javax.swing.JTextField();
        jCHoraIni = new javax.swing.JComboBox();
        jCHoraFim = new javax.swing.JComboBox();
        jBSalvar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"8-9", null, null, null, null, null, null},
                {"9-10", null, null, null, null, null, null},
                {"10-12", null, null, null, null, null, null},
                {"12-13", null, null, null, null, null, null},
                {"13-14", null, null, null, null, null, null},
                {"14-15", null, null, null, null, null, null},
                {"15-16", null, null, null, null, null, null},
                {"16-17", null, null, null, null, null, null},
                {"17-18", null, null, null, null, null, null},
                {"18-19", null, null, null, null, null, null},
                {"19-20", null, null, null, null, null, null},
                {"20-21", null, null, null, null, null, null}
            },
            new String [] {
                "", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Solicitação"));

        jCalendar1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {//GERA A AÇÃO PRA TROCA DE PROPRIEDADE  
            public void propertyChange(java.beans.PropertyChangeEvent evt) { //GERA EVENTO  
                jCalendar1PropertyChange(evt); //CHAMA O MÉTODO CONTENDO A ROTINA  
            }  
        });

        jLabel2.setText("Horário Início");

        jLabel3.setText("Horário Fim");

        jLabel4.setText("Data:");

        jLabel1.setText("Id Sala:");

        jLabel5.setText("Matricula Usuário:");

        jCHoraIni.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }));

        jCHoraFim.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }));

        jBSalvar.setText("Salvar");
        jBSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSalvarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jCalendar1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(44, 44, 44)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTData, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTIdSala, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTIdUser, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jCHoraIni, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jCHoraFim, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap())
                    .addComponent(jBSalvar)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTIdSala, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5)
                            .addComponent(jTIdUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jTData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(32, 32, 32)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jCHoraIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jCHoraFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jBSalvar))
                    .addComponent(jCalendar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSalvarActionPerformed
       verificaDados();
        try {
            cadastro();
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(null, "problemas no campo salvar" + ex);
        }
        JOptionPane.showMessageDialog(null, "Sala salva com sucesso!!");
    }//GEN-LAST:event_jBSalvarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:

        jTIdSala.setText(""+idsala);
        
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    private void jCalendar1PropertyChange(java.beans.PropertyChangeEvent evt) {

        SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy"); //DEFINE FORMATO DE DATA
        String data = formato.format(jCalendar1.getDate()); //CONVERTE PRA STRING
        jTData.setText(data);
       // jCalendar1.getda.setDecorationBackgroundColor(Color.yellow);
                //.setForeground(Color.yellow);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CadastroReserva().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBSalvar;
    private javax.swing.JComboBox jCHoraFim;
    private javax.swing.JComboBox jCHoraIni;
    private com.toedter.calendar.JCalendar jCalendar1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTData;
    private javax.swing.JTextField jTIdSala;
    private javax.swing.JTextField jTIdUser;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    public void cadastro() throws ParseException {

        try {
            Reserva res = new Reserva();

            String formato = "yyyy-MM-dd";
            SimpleDateFormat EUA = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat BRA = new SimpleDateFormat("dd-MM-yyyy");
            String data = EUA.format(BRA.parse(jTData.getText()));
       
            String horaIni = jCHoraIni.getSelectedItem().toString();
            String horaFim = jCHoraFim.getSelectedItem().toString();
            int horaI = Integer.parseInt(horaIni);
            int horaF = Integer.parseInt(horaFim);


            if (horaI < horaF) {
            res.setData(data);
            res.setIdSala(Integer.parseInt(jTIdSala.getText()));
            res.setMatSolic(Integer.parseInt(jTIdUser.getText()));

                if (horaI < 10) {
                    String hora = ("0" + horaI + ":00:00");

                    res.setHoraIni(hora);
                    System.out.println(" " + hora);
                } else {
                    String hora = (horaI + ":00:00");
                    res.setHoraFim(hora);
                    System.out.println(" " + hora);
                }
                if (horaF < 10) {
                    String hora = ("0" + horaFim + ":00:00");
                    res.setHoraIni(hora);
                    System.out.println(" " + hora);

                } else {
                    String hora = (horaFim + ":00:00");
                    res.setHoraFim(hora);
                    System.out.println(" " + hora);
                }

            } else {
                JOptionPane.showMessageDialog(null, "A hora de inicio não pode ser menor que a hora final!");
            }

            ReservaDAO dao = new ReservaDAO();
            dao.adiciona(res);

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "problemas no cadastro!!" + ex);
        }
    }

    public boolean verificaDados() {

        if (!jTData.getText().equals("") && !jTIdSala.getText().equals("") && !jTIdUser.getText().equals("")) {
            return true;
        } else {
            JOptionPane.showMessageDialog(null, "os campos nao podem ser nulos!!");
            return false;
        }


    }

    /* private void alteraReserva() throws SQLException {

    if (jTTabela.getSelectedRow() != -1) {
    if (verificaDados()) {
    Reserva res = new Reserva();
    ReservaDAO dao = new ReservaDAO();

    res.setId(Integer.parseInt(jTId.getText()));
    res.setAndar(Integer.parseInt(jTAndar.getText()));
    res.setNumLugares(Integer.parseInt(jTNumLugares.getText()));
    res.setPredio(jTPredio.getText());
    if (jCTipo.getSelectedItem() == "Reserva de aula") {
    res.setTipo("res de aula");
    }
    if (jCTipo.getSelectedItem() == "Reserva de reunião") {
    res.setTipo("res de reuniao");
    }
    if (jCTipo.getSelectedItem() == "Auditório") {
    res.setTipo("auditorio");
    }
    if (jCSituacao.getSelectedItem() == "Disponível") {
    res.setSituacao("disponivel");
    }
    if (jCSituacao.getSelectedItem() == "Alugada") {
    res.setSituacao("alugada");
    }


    dao.altera(res);
    JOptionPane.showMessageDialog(null, "res alterado com sucesso!");
    desabilitaDados();

    }
    }
    }

    public void excluirReserva() throws SQLException {
    int resp = JOptionPane.showConfirmDialog(this, "deseja realmente excluir esta Reserva", "confirmação: ", JOptionPane.YES_NO_OPTION);
    if (resp == JOptionPane.YES_NO_OPTION) { //por default, a resposta é sim!!
    ReservaDAO dao = new ReservaDAO();
    dao.remove(ress.get(jTTabela.getSelectedRow()));
    mostraPesquisa(ress);

    }

    }

    private void jTTabelaLinhaSelecionada(JTable tabela) {

    if (jTTabela.getSelectedRow() != -1) { //"-1" é o cod do erro quando se da quando exclui um contato
    habilitaDados();
    jBNovo.setEnabled(true);
    jBAlterar.setEnabled(true);
    jBSalvar.setEnabled(false);
    jBRemover.setEnabled(true);

    jTId.setText(String.valueOf(ress.get(tabela.getSelectedRow()).getId()));
    jTAndar.setText(String.valueOf(ress.get(tabela.getSelectedRow()).getAndar()));
    jTNumLugares.setText(String.valueOf(ress.get(tabela.getSelectedRow()).getNumLugares()));
    jTPredio.setText(ress.get(tabela.getSelectedRow()).getPredio());
    jCTipo.setSelectedItem(String.valueOf(ress.get(tabela.getSelectedRow()).getTipo()));
    jCSituacao.setSelectedItem(String.valueOf(ress.get(tabela.getSelectedRow()).getSituacao()));

    } else {
    jTId.setText("");
    jTAndar.setText("");
    jTNumLugares.setText("");
    jTPredio.setText("");

    }

    }

    private void mostraPesquisa(List<Reserva> ress) {

    while (tmReserva.getRowCount() > 0) { //vai pegar todas as linha selecionadas maiores que zero, é vai remove-las!
    tmReserva.removeRow(0);
    }
    if (ress.isEmpty()) { //se contatos for vazio, ou seja, naum haver nehum cadastrado...
    JOptionPane.showMessageDialog(null, "nehum res cadastrada");
    } else {
    String[] linha = new String[]{null, null, null, null, null, null}; //colocando null em todas as colunas
    for (int i = 0; i < res.size(); i++) {
    tmReserva.addRow(linha);
    tmReserva.setValueAt(res.get(i).getId(), i, 0);
    tmReserva.setValueAt(res.get(i).getTipo(), i, 1);
    tmReserva.setValueAt(res.get(i).getPredio(), i, 2);
    tmReserva.setValueAt(res.get(i).getAndar(), i, 3);
    tmReserva.setValueAt(res.get(i).getNumLugares(), i, 4);
    tmReserva.setValueAt(res.get(i).getSituacao(), i, 5);//"id", "tipo", "predio","andar", "Num.Lugares", "situação"
    }
    }
    }
     *
     */
   
}
